<template>
  <div class="createCampus">
    <el-form ref="campusForm" :model="campusForm" :rules="campusRules" label-width="120px">
      <el-form-item label="校区名称" prop="campusName">
        <el-input
          v-model="campusForm.campusName"
          placeholder="最多输入16个字"
          max="16"
          style="width:480px"
        />
      </el-form-item>
      <el-form-item label="校区地址" prop="territory">
        <!-- <el-cascader
          v-model="campusForm.territory"
          :options="territoryOptions"
          style="width:480px"
        />-->
        <el-select v-model="campusForm.province" placeholder="请选择省" @change="searchMap">
          <el-option
            v-for="item in provinceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="campusForm.city" placeholder="请选择市" @change="searchMap">
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="campusForm.district" placeholder="请选择区" @change="searchMap">
          <el-option
            v-for="item in districtOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="campusForm.address" style="width:480px" @keyup.enter.native="searchMap" />
        <el-button type="primary" @click="searchMap">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="map-list">
      <div class="map-label">地图定位</div>
      <div style="width: 800px;height:500px;" class="amap-demo">
        <el-amap
          id="mapcointainer"
          ref="map"
          :plugin="plugin"
          :events="events"
          :center="center"
          vid="amap"
        >
          <el-amap-marker
            v-for="(marker,index) in markers"
            :key="index"
            :events="marker.events"
            :position="marker.position"
            :visible="marker.visible"
            :draggable="marker.draggable"
          />
          <div id="panel" />
        </el-amap>
      </div>
    </div>
    <div class="stepBtn">
      <el-button @click="stepCancel">取消</el-button>
      <el-button type="primary" @click="stepConfirm">确定</el-button>
    </div>
  </div>
</template>

<script>
import { AMapManager } from 'vue-amap'
const amapManager = new AMapManager()
export default {
  data() {
    return {
      amapManager,
      campusId: '',
      selectClassDialog: false,
      campusForm: {
        campusName: '',
        // territory: [],
        province: '',
        city: '',
        district: '',
        address: ''
      },
      campusRules: {
        campusName: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
        territory: [{ required: true, message: '请选择课程', trigger: 'blur' }],
        address: [{ required: true, message: '请选择详细地址', trigger: 'blur' }]
      },
      provinceOptions: [
        {
          value: '上海市',
          label: '上海市'
        },
        {
          value: '广州市',
          label: '广州市'
        }
      ],
      cityOptions: [
        {
          value: '上海市区',
          label: '上海市区'
        }
      ],
      districtOptions: [
        {
          value: '浦东新区',
          label: '浦东新区'
        }
      ],

      center: [116.40, 39.90],
      loaded: false,
      events: {
        init: (o) => {
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all',
            city: '全国'
          })
          geocoder.getLocation(this.campusForm.address, (status, result) => {
            if (status === 'complete' && result.geocodes.length) {
              const lnglat = result.geocodes[0].location
              const lng = lnglat.lng
              const lat = lnglat.lat
              this.center = [lng, lat]
              this.markers[0].position = [lng, lat]
            }
          })
        },
        'click': (e) => {
          this.markers[0].position = [e.lnglat.lng, e.lnglat.lat]
          this.center = [e.lnglat.lng, e.lnglat.lat]
          var geocoder = new AMap.Geocoder({
            city: '010', // 城市设为北京，默认：“全国”
            radius: 1000 // 范围，默认：500
          })
          geocoder.getAddress(this.center, (status, result) => {
            if (status === 'complete' && result.regeocode) {
              var address = result.regeocode.formattedAddress
              this.campusForm.province = result.regeocode.addressComponent.province
              if (result.regeocode.addressComponent.city) {
                this.campusForm.city = result.regeocode.addressComponent.city
              } else {
                this.campusForm.city = result.regeocode.addressComponent.province + '区'
              }
              this.campusForm.district = result.regeocode.addressComponent.district
              this.campusForm.address = address
            } else {
              this.$message.error('根据经纬度查询地址失败')
            }
          })
        }
      },
      // 标记点
      markers: [
        {
          position: [116.397389, 39.908808],
          events: {
            click: () => {
              // alert('click marker')
            }
          },
          visible: true,
        }
      ],
      // map配置项
      plugin: [{
        zoom: 10,
        extensions: 'all',
        pName: 'ToolBar',
        events: {
          init(o) {
          }
        }
      }]

    }
  },
  mounted() {
    // 如果有id，获取id对应的数据
    this.campusId = this.$route.query.campusId
  },
  methods: {
    searchMap() {
      var map = this.amapManager.getMap()
      // var map = new AMap.Map("mapcointainer", {
      //   resizeEnable: false,
      //   zoom: 10
      // })
      AMap.service(['AMap.PlaceSearch'], () => {
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: '010', // 兴趣点城市
          citylimit: false, // 是否强制限制在设置的城市内搜索
          map: map, // 展现结果的地图实例
          panel: 'panel', // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        })
        placeSearch.search(this.campusForm.address || this.campusForm.province + this.campusForm.city + this.campusForm.district, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            // console.log(result)
            // this.result = result.poiList.pois
          }
        })
        AMap.event.addListener(placeSearch, "listElementClick", (e) => {
          var res = e.data
          this.campusForm.address = res.pname + res.cityname + res.adname + res.address
          this.center = [res.location.lng, res.location.lat]
          this.markers[0].position = [res.location.lng, res.location.lat]
          this.campusForm.province = res.pname
          this.campusForm.city = res.cityname + '区'
          this.campusForm.district = res.adname
        })
      })
    },
    stepCancel() {
      this.$refs.campusForm.resetFields()
      this.$router.go(-1)
    },
    stepConfirm() {
      // 提交表单
      this.$refs.campusForm.validate((valid) => {
        if (valid) {
          this.$refs.campusForm.resetFields()
          this.$router.go(-1)
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.createCampus {
  padding: 20px;
  padding-top: 40px;
  .stepBtn {
    margin: 40px 0 0 250px;
  }
  .map-list {
    display: flex;
    .map-label {
      width: 120px;
      text-align: right;
      padding-right: 12px;
      font-size: 14px;
      font-weight: 600;
      color: #606266;
    }
    .amap-demo {
      position: relative;
      #panel {
        position: absolute;
        background-color: white;
        // max-height: 90%;
        overflow-y: auto;
        top: 0px;
        right: -280px;
        width: 280px;
        height: 500px;
      }
    }
  }
}
</style>
